package base.多线程.同步代码.练习;

import javax.annotation.processing.RoundEnvironment;
import java.math.BigDecimal;
import java.util.Random;

public class Qhongbao implements Runnable{

    double money = 100;
    int count = 3;
    final double MIN = 0.01;

    @Override
    public void run() {
        synchronized (Qhongbao.class){
            try {
                Thread.sleep(700);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            String name = Thread.currentThread().getName();
            if (count == 0){
                System.out.println(name+"没抢到");
            }else {
                double price;

                Random r = new Random();
                double boundes = money - (count - 1) * MIN;

                BigDecimal bd = BigDecimal.valueOf(r.nextDouble(boundes));
                BigDecimal bdmoney = BigDecimal.valueOf(money);

                if (count == 1){
                    price = money;
                }else {

                    bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
                    price = Double.parseDouble(bd.toString());

                    //price = r.nextDouble(boundes);
                    if (price < MIN) price = MIN;
                }
                bdmoney = bdmoney.subtract(bd);
                money = Double.parseDouble(bdmoney.toString());
                count--;
                System.out.println(name+"抢到了"+price+'元');
            }
        }
    }
}
